# coding:utf-8
import random
import threading
import time
import tkinter as tk
import tkinter.messagebox as msgBox

import ttkbootstrap as tkBoot

from util.mysql_util import get_classes, get_students


class RandNameTab(tkBoot.Frame):
    def __init__(self, notebook):
        super().__init__(notebook)
        self.text = tk.StringVar()
        self.event = threading.Event()
        self.nameList = []
        self.notebook = notebook
        self.classes = get_classes(fetchNameProp=False)
        self.select = tkBoot.Combobox(self, value=list(map(lambda item: item[1], self.classes)), width=12)

    def initFrame(self):
        self.select.bind("<FocusIn>", lambda event: self.classesRefresh())
        self.select.pack(anchor=tk.NW, padx=(10, 0), pady=(10, 0))

        self.text.set("未知")
        label = tkBoot.Label(self, textvariable=self.text, font=("微软雅黑", 20))
        label.pack(side=tk.TOP, pady=(100, 0))

        btnFrame = tkBoot.Frame(self)
        buttonStart = tkBoot.Button(btnFrame, text="开始", command=self.start, width=10)
        buttonStart.pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.YES, padx=(0, 10))
        buttonStop = tkBoot.Button(btnFrame, text="结束", command=self.stop, width=10)
        buttonStop.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.YES)
        btnFrame.pack(side=tk.BOTTOM, pady=(0, 150))

        self.notebook.add(self, text="开始点名")
        self.notebook.select(self)

    def classesRefresh(self):
        self.classes = get_classes(fetchNameProp=False)
        self.select["values"] = list(map(lambda item: item[1], self.classes))

    def start(self) -> None:
        if self.select.current() is None:
            msgBox.showerror(message="请选择班级")
            return
        self.nameList = get_students(fetchNameProp=True, class_id=self.classes[self.select.current()][0])
        if len(self.nameList) == 0:
            msgBox.showerror(message="学生姓名数据为空")
        else:
            self.event.set()
            threading.Thread(target=self.loopRandom).start()

    def stop(self) -> None:
        for item in self.nameList:
            if self.text.get() == item:
                self.nameList.remove(item)
        self.event.clear()

    def loopRandom(self) -> None:
        while self.event.is_set():
            randName = self.nameList[random.randint(0, len(self.nameList) - 1)]
            self.text.set(randName)
            time.sleep(0.1)
